package com.gzx.plugin.website.xxl;

import cn.hutool.core.collection.CollectionUtil;
import com.gzx.plugin.website.access.entity.GzxAccessLog;
import com.gzx.plugin.website.access.service.GzxAccessLogService;
import com.gzx.plugin.website.user.entity.GzxWebsiteUserLog;
import com.gzx.plugin.website.user.service.GzxWebsiteUserLogService;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import vip.xiaonuo.common.cache.CommonCacheOperator;
import vip.xiaonuo.common.tenant.TenantContext;
import vip.xiaonuo.common.util.CommonCryptogramUtil;

import java.util.ArrayList;
import java.util.List;

/**
 * @author zjt
 * @description
 * @date 2025/4/21 13:37
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class SyncOldAccessXxlJob {

    private final GzxAccessLogService accessLogService;

    private final GzxWebsiteUserLogService websiteUserLogService;

    private final CommonCacheOperator cacheOperator;

    @XxlJob("syncOldAccessJobHandler")
    public void syncOldAccessJobHandler() {
        String currentId = cacheOperator.getCatchString("WebsiteAccessCurrentId");
        if (StringUtils.isBlank(currentId)) {
            currentId = "0";
        }
        List<GzxAccessLog> accessLogList = new ArrayList<>();
        try {
            TenantContext.disableTenantFilter();
            List<GzxWebsiteUserLog> websiteUserLogList = websiteUserLogService.list(Long.valueOf(currentId));
            if (CollectionUtil.isNotEmpty(websiteUserLogList)) {
                for (GzxWebsiteUserLog websiteUserLog : websiteUserLogList) {
                    // 字段映射转换‌
                    GzxAccessLog accessLog = new GzxAccessLog();
                    accessLog.setDebtorCardId(CommonCryptogramUtil.doSm1AesEncrypt(websiteUserLog.getAccuserIdCard()));
                    accessLog.setLiaisonPhone(CommonCryptogramUtil.doSm1AesEncrypt(websiteUserLog.getMobile()));
                    accessLog.setChannel(websiteUserLog.getChannel());
                    accessLog.setCreateTime(websiteUserLog.getCreateTime());
                    accessLog.setIp(websiteUserLog.getIp());
                    accessLogList.add(accessLog);
                    // 更新最大ID
                    if (websiteUserLog.getId() > Long.parseLong(currentId)) {
                        currentId = String.valueOf(websiteUserLog.getId());
                    }
                }
            }
            accessLogService.insertBatch(accessLogList);
            cacheOperator.setCatchString("WebsiteAccessCurrentId", String.valueOf(currentId));
        } catch (Exception e) {
            log.error("同步老数据失败", e);
        } finally {
            TenantContext.clear();
        }
    }
}
